/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦，本文采用木兰宽松许可证第2版]
 * 
 * https://zhiqim.org/project/zhiqim_kit/zhiqim_git.htm
 *
 * ZhiqimGit is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.zhiqim.git.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.zhiqim.git.GitConstants;
import org.zhiqim.git.objer.PackIndex;

import org.zhiqim.kernel.util.Asserts;
import org.zhiqim.kernel.util.Bytes;
import org.zhiqim.kernel.util.Streams;

public class GitObjects implements GitConstants
{
    /** 
     * 通过索引文件获取包文件
     * 
     * @param           索引文件名
     * @return          包文件名
     */
    public static String getPackFileName(String indexName)
    {
        return indexName.substring(0, indexName.length() - 4) + _PACK;
    }
    
    /**
     * 读取包索引文件前8字节，判断是否是TOC－V2版本，是则创建索引类，否则异常
     * 
     * @param idxFile       索引文件
     * @return              索引类
     * @throws IOException  IO异常
     */
    public static PackIndex build(File idxFile) throws IOException
    {
        try(FileInputStream in = new FileInputStream(idxFile))
        {
            byte[] hdr = Streams.getBytes(in, 8);
            Asserts.asserts(isTOC(hdr), "当前仅支持索引TOC版本＝2");
            
            int v = Bytes.BU.getInt(hdr, 4);
            Asserts.asserts(v == 2, "当前仅支持索引TOC版本＝2");
            return new PackIndex(in);
        }
        catch (IOException e)
        {
            throw new IOException("读取包索引文件IO异常: " + idxFile.getAbsolutePath(), e);
        }
    }
    
    /**
     * 判断是否是包索引文件头信息
     * 
     * @param h         头字节数组
     * @return          =true表示索引V2
     */
    public static boolean isTOC(final byte[] h)
    {
        for (int i=0;i<TOC.length;i++)
        {
            if (h[i] != TOC[i])
                return false;
        }
        
        return true;
    }
}
